package cn.net.xyan.easy.spring.web.controller;

import cn.net.xyan.easy.spring.web.config.MVCApplicationContextConfig;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;
import org.webjars.RequireJS;
import org.webjars.WebJarAssetLocator;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by xiashenpin on 16/1/17.
 */
@Controller
public class WebJarController {

    WebJarAssetLocator assetLocator;

    @PostConstruct
    public void setup(){
        assetLocator = new WebJarAssetLocator();
    }

    @ResponseBody
    @RequestMapping(value = MVCApplicationContextConfig.WEBJARROOT+"{webjar}/**")
    public ResponseEntity locateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
        try {
            String mvcPrefix = MVCApplicationContextConfig.WEBJARROOT + webjar + "/"; // This prefix must match the mapping path!
            String mvcPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
            String fullPath = assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length()));
            return new ResponseEntity(new ClassPathResource(fullPath), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    @RequestMapping(value = MVCApplicationContextConfig.WEBJARROOT+"webjar.js", produces = "application/javascript")
    public @ResponseBody  String webjarjs() {
        return RequireJS.getSetupJavaScript(MVCApplicationContextConfig.WEBJARROOT);
    }

    @RequestMapping(value = MVCApplicationContextConfig.WEBJARROOT+"webjar.json", produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody
    Map<String, ObjectNode> webjarjson() {
        return RequireJS.getSetupJson(MVCApplicationContextConfig.WEBJARROOT);
    }
}
